<template>
  <div class="app-container">
    <div class="top" style="margin-top: 28px;">
      <el-button type="success" class="el-icon-plus add-btn" @click="handleShowTopicAmazon">框架关键词
      </el-button>
      <el-button type="primary" class="el-icon-plus add-btn" @click="handleAddNew">手动添加
      </el-button>
    </div>

    <el-table
      ref="table"
      :data="data"
      border
      highlight-current-row
      style="width: 100%;"
      height="600"
      :default-sort="{prop: 'score', order: 'descending'}"
    >
      <el-table-column
        type="index"
        width="50"
      />
      <el-table-column align="center" label="图片">
        <template slot-scope="scope">
          <span><img :src="scope.row.image" style="width: 100px; height: 100px"></span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="url">
        <template slot-scope="scope">
          <el-input
            v-show="scope.row.edit"
            v-model="scope.row.url"
            placeholder="url"
            class="edit-input"
            size="small"
          />
          <span v-if="!scope.row.edit"><a target="_blank" :href="scope.row.url">{{ scope.row.url }}</a></span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="aff">
        <template slot-scope="scope">
          <span v-if="!scope.row.edit">{{ scope.row.aff_link }}</span>
          <el-input
            v-show="scope.row.edit"
            v-model="scope.row.aff_link"
            placeholder="url"
            class="edit-input"
            size="small"
          />
        </template>
      </el-table-column>
      <el-table-column align="center" label="score" prop="score" width="120" sortable>
        <template slot-scope="scope">
          <span v-if="!scope.row.edit">{{ scope.row.score }}</span>
          <el-input
            v-show="scope.row.edit"
            v-model="scope.row.score"
            placeholder="url"
            class="edit-input"
            size="small"
          />
        </template>
      </el-table-column>
      <el-table-column align="center" label="price" prop="price" width="100" />
      <el-table-column align="center" label="reviews" prop="reviews" width="100" />
      <el-table-column align="center" label="信息修改" width="260">
        <template slot-scope="scope">
          <el-input
            v-show="scope.row.edit"
            v-model="scope.row.title"
            placeholder="修改产品标题"
            class="edit-input"
            size="small"
          />
          <el-input
            v-show="scope.row.edit"
            v-model="scope.row.brand"
            placeholder="brand"
            class="edit-input"
            size="small"
          />
          <span v-show="!scope.row.edit">{{ scope.row.title }}<br>{{ scope.row.brand }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作" width="350" fixed="right">
        <template slot-scope="scope">
          <el-button
            v-show="scope.row.edit"
            class="cancel-btn"
            size="mini"
            icon="el-icon-refresh"
            type="warning"
            @click="scope.row.edit=false"
          >完成
          </el-button>

          <el-button
            v-show="!scope.row.edit"
            type="primary"
            size="mini"
            icon="el-icon-edit"
            @click="scope.row.edit=!scope.row.edit"
          >
            修改
          </el-button>
          <el-button type="success" size="mini" :loading="scope.row.loading" @click="CrawlItem(scope.row)">
            抓取内容
          </el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>

    </el-table>
    <hr>
    <el-row>
      <el-button style="margin: 10px;float: right;" type="success" :loading="listLoading" @click="GetHtml">批量抓取</el-button>
      <el-button style="margin: 10px;float: right;" type="success" @click="CombinaHtml">组合代码</el-button>
    </el-row>
    <el-drawer
      title="博客代码"
      :wrapper-closable="false"
      append-to-body
      size="60%"
      :visible.sync="drawer"
      direction="btt"
    >
      <div style="padding-left: 40px; padding-right: 40px">
        <el-row>
          <el-col :span="12">
            <h4>生成代码</h4>
            <textarea v-model="code" rows="20" style="width: 100%" />
          </el-col>
          <el-col :span="12">
            <h4>保存&发布-- {{ keyword }}</h4>
            <el-row :gutter="5">
              <el-col :xs="24" :sm="12" :md="12" :lg="3" :xl="3">
                <div class="grid-content bg-purple">
                  <el-select
                    v-model="project_id"
                    v-loading="projectsLoading"
                    placeholder="项目"
                    size="mini"
                    class="head"
                    clearable
                  >
                    <el-option
                      v-for="item in projects"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>
                </div>
              </el-col>
              <el-col :xs="24" :sm="12" :md="12" :lg="3" :xl="3">
                <div class="grid-content bg-purple">
                  <el-select
                    v-model="category_id"
                    v-loading="categoriesLoading"
                    placeholder="分类"
                    size="mini"
                    class="head"
                    clearable
                  >
                    <el-option
                      v-for="category in categories"
                      :key="category.id"
                      :label="category.name"
                      :value="category.id"
                    />
                  </el-select>
                </div>
              </el-col>
              <el-col :xs="24" :sm="12" :md="12" :lg="3" :xl="3">
                <div class="grid-content bg-purple">
                  <el-select
                    v-model="language_id"
                    v-loading="languagesLoading"
                    placeholder="语言"
                    size="mini"
                    class="head"
                    clearable
                  >
                    <el-option
                      v-for="language in languages"
                      :key="language.id"
                      :label="language.name"
                      :value="language.id"
                    />
                  </el-select>
                </div>
              </el-col>
              <el-col :xs="24" :sm="12" :md="12" :lg="10" :xl="10">
                <el-select
                  v-model="selected_webs"
                  v-loading="websLoading"
                  size="mini"
                  placeholder="输出站点"
                  multiple
                  clearable
                  filterable
                  style="width: 60%;"
                >
                  <el-option
                    v-for="web in webs"
                    :key="web.id"
                    :label="web.url"
                    :value="web.id"
                  />
                </el-select>
                <el-button icon="el-icon-refresh" size="mini" title="刷新" type="info" @click="handleFetchWebs" />
              </el-col>
            </el-row>
            <el-row>
              <el-input v-model="post_id" placeholder="请输博客id获取" class="input-with-select">
                <el-button slot="append" :loading="postloading" icon="el-icon-search" @click="handleGetPosts">载入博客内容</el-button>
              </el-input>
              <el-button v-if="post_id !== ''" type="success" @click="postEditorVisible=true">编辑博客</el-button>
            </el-row>
            <el-row>
              <el-input v-model="title" style="display: inline-block" placeholder="输入标题保存内容" />
            </el-row>
            <el-row style="margin-top: 20px">
              <el-alert
                v-if="showAlarm1"
                title="博客内容已经添加到文章末尾，并保存，可以直接发布"
                type="warning"
              />
              <el-button v-if="title !== ''" style="margin-right: 10px" type="success" @click="handleClickSave('1')">保存</el-button>
              <el-button v-if="post_id !== ''" style="margin-right: 10px" type="primary" @click="handleClickPublish">发布到wodpress</el-button>
              <el-button style="margin-right: 10px" type="error" @click="cleanData">清空数据</el-button>
            </el-row>
          </el-col>
        </el-row>
      </div>

    </el-drawer>
    <el-dialog
      :title="newDialogTitle"
      :visible.sync="newDialogVisible"
      width="40%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form
        ref="renewForm"
        :model="form"
        label-position="left"
        label-width="40px"
        style="margin-left: 8%"
      >
        <el-form-item label="aff-tag" label-width="80px">
          <el-input v-model="form.aff_tag" />
        </el-form-item>
        <el-form-item label="产品链接" label-width="80px">
          <el-input v-model="form.url" type="textarea" rows="5" @change="handleModifyAffLink" />
        </el-form-item>
        <el-form-item label="aff link" label-width="80px">
          <el-input v-model="form.aff_link" />
        </el-form-item>

      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="newDialogVisible = false">取 消</el-button>
        <el-button type="primary" :loading="itemloading" @click="HandleAdd">确 定</el-button>

      </span>
    </el-dialog>
    <wppromote
      :promote-visiable="promoteVisiable"
      :project_id="project_id"
      :post_id="post_id"
      @closewppromoteDialog="promoteVisiable=false"
    />
    <topic_amazon_product :search_query="keyword" :web-visible="topicAmazonVisible" @close="topicAmazonVisible = false" @add_products="handleAddReviewItems" />
    <post_editor :post_id="post_id" :post-editor-visible="postEditorVisible" @close="postEditorVisible=false" />
  </div>
</template>

<script>
import { Get as GetProjects } from '@/api/erp/elicink/project'
import { Get as GetCategories } from '@/api/cms/category'
import { Get as GetLanguages } from '@/api/cms/language'
import { Get as GetWebs } from '@/api/cms/web'
import { Get as GetPost, Post as AddPost, Put as PutPost } from '@/api/cms/post'
import { BestReviews_Generator } from '@/api/cms/html_generator'
// import Tinymce from '@/components/Tinymce'
import Cookies from 'js-cookie'
import Wppromote from './elements/wppromote'
import Topic_amazon_product from './elements/topicamazonproduct'
import Post_editor from './elements/posteditor'
export function getToken(key) {
  const v = Cookies.get(key)
  return v && parseInt(v) || null
}

export function setToken(key, value) {
  return Cookies.set(key, value, { expires: 30 })
}

const ProjectKey = 'cms_project_id'
const CategoryKey = 'cms_category_id'
const LanguageKey = 'cms_language_id'

export default {
  name: 'Bestreviewhtml',
  components: { Post_editor, Topic_amazon_product, Wppromote },
  // components: { Tinymce },
  data() {
    return {
      showAlarm1: false,
      postEditorVisible: false,
      tapVisible: false,
      topicAmazonVisible: false,
      title: '',
      promoteVisiable: false,
      pageLoading: false,
      postloading: false,
      post_id: '',
      project_id: null,
      projects: [],
      projectsLoading: false,
      topic_description: '',
      categories: [],
      category_id: null,
      categoriesLoading: false,
      webs: [],
      selected_webs: [],
      websLoading: false,
      languages: [],
      language_id: null,
      languagesLoading: false,
      newDialogTitle: '添加新产品',
      drawer: false,
      itemloading: false,
      code: '',
      newDialogVisible: false,
      form: {
        'url': '',
        'aff_link': '',
        'aff_tag': '',
        'score': '',
        'image': '',
        'brand': '',
        'title': '',
        loading: false,
        code: ''
      },
      data: [],
      listLoading: false
    }
  },
  computed: {
    // 默认关键词
    keyword: function() {
      return this.$route.query.k
    }
  },
  created() {
    // console.log(this.$route.query.k)
    this.form.aff_tag = Cookies.get('bvhtm_tag') || ''
    this.handleFetchProjects()
    this.handleFetchCategories()
    this.handleFetchLanguages()
    this.handleFetchWebs()
    this.project_id = getToken(ProjectKey)
    this.category_id = getToken(CategoryKey)
    this.language_id = getToken(LanguageKey)
  },
  methods: {
    handleAddReviewItems(args) {
      this.form.url = args.urls.join('\n')
      this.post_id = args.post_id
      this.keyword = args.keyword
      this.handleAddNew()
    },
    get_clean_amazon_url(url) {
      var url_obj = new URL(url)
      let asin = ''
      var regex = RegExp(url_obj.origin + '/([\\w-]+/)?(dp|gp/product)/(\\w+/)?(\\w{10})')
      var m = url.match(regex)
      if (m) {
        asin = m[4]
      }
      if (asin !== '') {
        return url_obj.origin + '/dp/' + asin + '/'
      } else {
        return url
      }
    },
    handleDelete(index, row) {
      for (let i = 0; i < this.data.length; i++) {
        if (this.data[i].url === row.url) {
          console.log('remove ', row.url)
          if (this.data.length === 10) {
            this.$confirm(`继续删除将不足10个产品，确定要删除吗?`, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.data.splice(i, 1)
              this.$message.success('删除成功,剩余产品:' + this.data.length)
            })
          } else {
            this.data.splice(i, 1)
            this.$message.success('删除成功,剩余产品:' + this.data.length)
          }
        }
      }
    },
    handleShowTopicAmazon() {
      this.topicAmazonVisible = true
    },
    handleAddNew() {
      this.newDialogTitle = '添加第' + (this.data.length + 1) + '个产品'
      this.newDialogVisible = true
    },
    CombinaHtml() {
      this.data.sort((a, b) => { return b.score - a.score })
      // 注意要使用wphtml注释，否则代码可能会被过滤
      let html = '<ol class="tbbg_aff_product__list">'
      let how_we_score = `<div class="tbbg_aff_product__item-container" front-role="product_list_object"><div class="tbbg_aff_product__item " data-action="Click How We Score Card" data-label="4" id="editorial_score_card">`
      how_we_score += `<div class="editorial_score_card__circle blue"><span>7.6</span><br><small>Reviews</small></div><div class="editorial_score_card__title">How we Score</div>`
      how_we_score += `<div class="editorial_score_card__circle darkblue"><span>9.8</span><br><small>features quality</small></div><div class="editorial_score_card__circle yellow"><span>8.8</span><br>`
      how_we_score += `<small>popularity</small></div><div class="editorial_score_card__circle green"><span>8.1</span><br><small>brand reputation</small>`
      how_we_score += `</div><div class="editorial_score_card__unclicked"><div class="editorial_score_card__learn-more">learn more</div></div>`
      how_we_score += `<div class="editorial_score_card__clicked"><div class="editorial_score_card__close">close x</div><div class="editorial_score_card__text">We considers online reviews, products popularity, social and groups reviews, brand reputation, prices, and many more factors, as well as reviews by our experts.</div></div></div></div>`
      for (let i = 0; i < this.data.length; i++) {
        if (this.data[i].code) {
          if (i === 4) {
            html += how_we_score
          }
          html += `<li class="tbbg_aff_product__item-container" data-price="` + this.data[i].price + `"><div class="tbbg_aff_product__item desktop">`
          html += `<aside class="tbbg_aff_product__badge-wrapper desktop"><span class="tbbg_aff_product__position desktop" front-role="product_position">` + (i + 1) + `</span></aside>`
          // left div
          html += `<div class="tbbg_aff_product__item__left">`
          html += `<div class="tbbg_aff_product__img__wrapper desktop"><a class="clickout tbbg_aff_product_card__img-wrapper" target="_blank" rel="nofollow noopener" referrerpolicy="no-referrer-when-downgrade" href="${this.data[i].aff_link}" ><img class="tbbg_aff_product__img desktop" alt="` + this.data[i].title + `" src="` + this.data[i].image + `" data-was-processed="true"></a></div></div>`
          // end left div
          // middle div
          html += `<div class="tbbg_aff_product__item__center tbbg_aff_product__item__center--prime-small">`
          html += `<div class="tbbg_aff_product__title--container long_title"><div class="tbbg_aff_product__title desktop"><a target="_blank" href="` + this.data[i].aff_link + `" class="clickout tbbg_aff_product_card__brand-wrapper narrow">` + this.data[i].title + `</a></div></div>`
          html += `<div class="tbbg_aff_product__brand desktop"><a target="_blank" href="` + this.data[i].aff_link + `" class="clickout tbbg_aff_product_card__brand-wrapper narrow">` + this.data[i].brand + `</a></div></div>`
          // right div
          html += `<div class="tbbg_aff_product__item__right"><div class="tbbg_aff_product__score_wrapper narrow"><div class="tbbg_aff_product__score desktop">` + this.data[i].score + `</div></div> <div class="bottom tbbg_aff_product__flex-wrapper">`
          html += `<a target="_blank" class="clickout tbbg_aff_product_card__cta-button-wrapper" target="_blank" rel="nofollow" referrerpolicy="no-referrer-when-downgrade" href="` + this.data[i].aff_link + `"> <button class="tbbg_aff_product__button desktop"><span>more info</span></button> </a>`
          html += `</div><div class="tbbg_aff_deals__buy-it-amazon"> <a  target="_blank" class="clickout buy-it-on-amazon" target="_blank" rel="nofollow" referrerpolicy="no-referrer-when-downgrade" href="` + this.data[i].aff_link + `">Buy it Now</a></div></div></div></li>`
        }
      }
      this.code = html + '</ol>'
      // console.log(html)
      // this.$refs.mt.setContent(this.code)
      this.drawer = true
    },
    CrawlItem(row) {
      this.itemloading = true
      this.$message('开始后台提取产品信息......')
      BestReviews_Generator({ items: [row] }).then(response => {
        if (response.data && response.data.length >= 1) {
          row.image = response.data[0].image
          row.brand = response.data[0].brand
          row.title = response.data[0].title
          row.price = response.data[0].price
          row.reviews = response.data[0].reviews
          row.score = response.data[0].score
          row.code = response.data[0].code
        }
        this.form.url = ''
        this.form.aff_link = ''
        this.itemloading = false
        this.newDialogTitle = '添加第' + (this.data.length + 1) + '个产品'
        this.$message({
          message: '爬取内容成功',
          type: 'success'
        })
      }).catch(error => {
        this.itemloading = false
        console.log(error)
      })
    },
    GetHtml() {
      this.listLoading = true
      BestReviews_Generator({ items: this.data }).then(response => {
        this.code = response.code
        // this.$nextTick(() => {
        // this.$refs.mt.setContent(this.code)
        this.drawer = true
        // })
        this.listLoading = false
        this.notify('生成成功')
      }).catch(error => {
        this.listLoading = false
        console.log(error)
      })
    },
    get_aff_link(url, aff_tag) {
      if (aff_tag) {
        Cookies.set('bvhtm_tag', aff_tag)
      }
      if (url.indexOf('?') !== -1) {
        return url + '&tag=' + aff_tag
      } else {
        return url + '?tag=' + aff_tag
      }
    },
    handleModifyAffLink() {
      if (this.form.url.indexOf('http') === -1) {
        this.$message.error('请输入正确得链接')
        return
      }
      if (this.form.url.indexOf('\n') !== -1) {
        return
      }
      this.form.url = this.get_clean_amazon_url(this.form.url)
      this.form.aff_link = this.get_aff_link(this.form.url, this.form.aff_tag)
    },
    is_url_exists(url) {
      for (let i = 0; i < this.data.length; i++) {
        if (this.data[i].url === url) {
          return true
        }
      }
      return false
    },
    HandleAdd() {
      const item = Object.assign({}, this.form)
      item.edit = false
      item.loading = false
      if (this.form.url === '') {
        return
      }
      if (this.form.url.indexOf('http') === -1) {
        this.$message.error('请输入正确得链接')
        return
      }
      const urls = this.form.url.split('\n')
      if (urls.length > 0) {
        console.log('total ' + urls.length)
        for (let i = 0; i < urls.length; i++) {
          const new_item = Object.assign({}, this.form)
          urls[i] = this.get_clean_amazon_url(urls[i])
          console.log(urls[i])
          if (urls[i].trim() === '') {
            continue
          }
          if (urls[i].indexOf('http') === -1) {
            continue
          }
          if (this.is_url_exists(urls[i].trim())) continue
          new_item['url'] = urls[i].trim()
          new_item['aff_link'] = this.get_aff_link(urls[i], this.form.aff_tag)
          this.data.push(new_item)
          this.CrawlItem(new_item)
        }
      } else {
        if (this.is_url_exists(item.url.trim())) {
          this.$message.error('url已经存在')
          return
        }
        this.data.push(item)
        this.CrawlItem(item)
      }
    },
    notify(message, duration) {
      this.$notify({
        title: '成功',
        message: message,
        type: 'success',
        duration: duration || 2000
      })
    },
    // posts
    cleanData() {
      this.post_id = ''
      this.code = ''
      this.title = ''
      this.showAlarm1 = false
      this.data = []
    },
    handleGetPosts() {
      if (this.post_id === '') {
        return
      }
      this.postloading = true
      GetPost(this.post_id)
        .then(response => {
          this.project_id = response.data.project_id
          this.category_id = response.data.category_id
          this.language_id = response.data.language_id
          this.webs = response.data.webs
          this.code += response.data.content
          if (this.title === '') {
            this.title = response.data.title
          }
          this.postloading = false
          this.$message.success('载入内容成，已经添加到文章末尾')
          this.handleClickSave('1')
          this.showAlarm1 = true
        })
        .catch(e => {
          this.postloading = false
        })
    },
    handleClickSave(loading) {
      let version_name = ''
      if (loading === '1') {
        this.pageLoading = true
      } else if (loading === '2') {
        this.pageLoading = true
        version_name = prompt('版本名称:')
        if (!version_name) {
          version_name = ''
        }
      }

      const vars = {
        project_id: this.project_id,
        category_id: this.category_id,
        language_id: this.language_id,
        source_id: this.source_id,
        webs: this.selected_webs,
        title: this.title,
        content: this.code,
        version_name: version_name,
        word_count: 100
      }

      const x = this.post_id ? PutPost(this.post_id, JSON.stringify(vars)) : AddPost(JSON.stringify(vars))
      x.then(response => {
        this.pageLoading = false
        if (response.data) this.post_id = response.data
        this.$message({
          message: 'post保存成功ID:' + this.post_id,
          type: 'success'
        })
        const promise = new Promise(function(resolve, reject) {
          resolve()
        })
        promise.then(this.setCookies())
      }).catch(e => {
        this.pageLoading = false
      })
      // this.$nextTick(() => {
      //   this.$refs.mt.insertContent('abc<img alt="Smiley face" height="42" width="42" src=""/>')
      // })
    },
    setCookies() {
      if (this.project_id) setToken(ProjectKey, this.project_id)
      if (this.category_id) setToken(CategoryKey, this.category_id)
      if (this.language_id) setToken(LanguageKey, this.language_id)
    },
    handleClickPublish() {
      this.promoteVisiable = true
    },
    handleFetchProjects() {
      this.projectsLoading = true
      GetProjects()
        .then(response => {
          this.projectsLoading = false
          this.projects = response.data.data
        })
        .catch(e => {
          this.projectsLoading = false
        })
    },
    handleFetchCategories() {
      this.categoriesLoading = true
      GetCategories()
        .then(response => {
          this.categoriesLoading = false
          this.categories = response.data.data
        })
        .catch(e => {
          this.categoriesLoading = false
        })
    },
    handleFetchLanguages() {
      this.languagesLoading = true
      GetLanguages()
        .then(response => {
          this.languagesLoading = false
          this.languages = response.data.data
        })
        .catch(e => {
          this.languagesLoading = false
        })
    },
    handleFetchWebs() {
      this.websLoading = true
      GetWebs()
        .then(response => {
          this.websLoading = false
          this.webs = response.data.data
        })
        .catch(e => {
          this.websLoading = false
        })
    }
  }
}
</script>

<style scoped>

.el-tag + .el-tag {
  margin-left: 10px;
}

.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}

.input-with-select {
  width: calc(100% - 200px);
}

.add-btn {
  float: right;
  margin-right: 20px;
  width: 130px
}

.top {
  padding-left: 20px;
  margin-bottom: 30px;
}

.mt-pagination {
  float: right;
  margin-top: 5px;
}

.app-container >>> span.el-tag--info {
  word-break: normal;
  width: auto;
  display: block;
  white-space: pre-wrap;
  word-wrap: break-word;
  overflow: hidden;
}
</style>

